package wechat;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.Configuration;
import org.weixin4j.User;
import org.weixin4j.WXPayUtil;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.WXPayConstants.SignType;
import org.weixin4j.http.OAuth2Token;
import org.weixin4j.pay.JsApiTicket;
import org.weixin4j.pay.SignUtil;
import org.weixin4j.ticket.TicketType;
import org.weixin4j.web.AdvancedUtil;

import com.common.CommonUtil;
import com.common.ResultData;
import com.filter.BaseController;

import beans.subject.subsetquestion;
import beans.subject.subsetquestionsubject;
import beans.sys.SYSCodeBean;
import beans.user.order;
import beans.user.suberror;
import beans.user.user;
import beans.user.xh;
import beans.user.xhlog;
import service.subject.SubSetQuestionImpl;
import service.subject.SubSetQuestionSubjectImpl;
import service.sys.SYSCodeServiceImpl;
import service.user.OrderServiceImpl;
import service.user.SubErrorServiceImpl;
import service.user.WXUserServiceImpl;
import service.user.XHLogServiceImpl;
import service.user.XHServiceImpl;

@Controller
@RequestMapping("/wx")
public class WXHomeController  extends BaseController{
	@Resource
	private WXUserServiceImpl<user> wxUserServiceImpl;
	@Resource
	private OrderServiceImpl<order> orderServiceImpl;

	@Resource
	private SubErrorServiceImpl<suberror> subErrorServiceImpl;

	@Resource
	private XHServiceImpl<xh> xhServiceImpl;
	@Resource
	private XHLogServiceImpl<xhlog> xhLogServiceImpl;
	@Resource
	private SYSCodeServiceImpl<SYSCodeBean> sYSCodeServiceImpl;
	
	Logger logger= Logger.getLogger(WXHomeController.class);
	
	@RequestMapping("/index")
	public String Index() throws Exception{

		List<order> orderList = orderServiceImpl.getPayInfo();
		for(order o :orderList) {
			if(!CommonUtil.isNullObject(o.getNickname())) {
				if(o.getNickname().length()>8)
					o.setNickname(o.getNickname().substring(0, 7)+"*");
				else
					o.setNickname(o.getNickname().substring(0, o.getNickname().length()-1)+"*");
			}
		}
		getReq().getSession().setAttribute("orderList", orderList);

		String code = getReq().getParameter("code");

		//if(null != code && !"".equals(code)){
			logger.error("直接输出吧---------"+code);
			//根据code换取openId
			//OAuth2Token oa = AdvancedUtil.getOauth2AccessToken(Configuration.getOAuthAppId(), Configuration.getOAuthSecret(),code);
			//if(!"".equals(oa) && null != oa){
				user temUser = wxUserServiceImpl.queryById("1234567890");
//				if(temUser==null) {
//					User u = AdvancedUtil.getSNSUserInfo(oa.getAccess_token(), oa.getOpenid());
//					temUser = new user();
//					temUser.setId(UUID.randomUUID().toString());
//					temUser.setOpenid(oa.getOpenid());
//					temUser.setCity(u.getCity());
//					temUser.setCountry(u.getCountry());
//					temUser.setGroupid(u.getGroupid());
//					temUser.setHeadimgurl(u.getHeadimgurl());
//					temUser.setLanguage(u.getLanguage());
//					temUser.setNickname(u.getNickname());
//					temUser.setProvince(u.getProvince());
//					temUser.setRemark(u.getRemark());
//					temUser.setSex(String.valueOf(u.getSex()));
//					temUser.setSubscribe(u.getSubscribe());
//					temUser.setSubscribe_time(new Date(u.getSubscribe_time()*1000L));
//					temUser.setQr_scene_str(u.getQr_scene_str());
//					wxUserServiceImpl.add(temUser);
//					
//					getReq().getSession().setAttribute("wxuser", temUser);
//				}
//				else 
					getReq().getSession().setAttribute("wxuser", temUser);
				return "wechat/home/index";
//			}else{//登录失败
//				return "wechat/home/noright";
//			}
//		}
//		else{
//			user u = (user)getReq().getSession().getAttribute("wxuser");
//			if(u==null)
//				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configuration.getOAuthAppId()+"&redirect_uri=http%3a%2f%2f2.zydkj.net.cn%2fwx%2findex&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
//			else
//				return "wechat/home/index";
//		}
	}

	/***
	 * 我的错题
	 * @return
	 */
	@RequestMapping("/err")
	public String MyError(){
		user u = (user)getReq().getSession().getAttribute("wxuser");
		String c11 = "0";
		String c14 = "0";
		String a21 = "0";
		String a24 = "0";
		String a11 = "0";
		String a14 = "0";
		String d1 = "0";
		String d4 = "0";
		try {
			List<Map> list = subErrorServiceImpl.getByUser(u.getId());
			for(Map m : list) {
				if(m.get("exam").equals("C1-C2")&&m.get("examtype").equals("科目一"))c11 = m.get("count").toString();
				else if(m.get("exam").equals("C1-C2")&&m.get("examtype").equals("科目四"))c14 = m.get("count").toString();

				else if(m.get("exam").equals("A2-B2")&&m.get("examtype").equals("科目一"))a21 = m.get("count").toString();
				else if(m.get("exam").equals("A2-B2")&&m.get("examtype").equals("科目四"))a24 = m.get("count").toString();

				else if(m.get("exam").equals("A1-A3-B1")&&m.get("examtype").equals("科目一"))a11 = m.get("count").toString();
				else if(m.get("exam").equals("A1-A3-B1")&&m.get("examtype").equals("科目四"))a14 = m.get("count").toString();

				else if(m.get("exam").equals("D-E-F")&&m.get("examtype").equals("科目一"))d1 = m.get("count").toString();
				else if(m.get("exam").equals("D-E-F")&&m.get("examtype").equals("科目四"))d4 = m.get("count").toString();
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		getReq().setAttribute("c11", c11);
		getReq().setAttribute("c14", c14);
		getReq().setAttribute("a21", a21);
		getReq().setAttribute("a24", a24);
		getReq().setAttribute("a11", a11);
		getReq().setAttribute("a14", a14);
		getReq().setAttribute("d1", d1);
		getReq().setAttribute("d4", d4);
		return "wechat/home/err";
	}

	/**
	 * 我的序号
	 * @return
	 */
	@RequestMapping("/xh")
	public String MyXH(String url){
		user u = (user)getReq().getSession().getAttribute("wxuser");
		xh _xh = xhServiceImpl.getByUserid(u.getOpenid());
		Date now = new Date();
		if(_xh!=null&&now.before(_xh.getLasttime())&&_xh.getLastcount()>0) {
			getReq().setAttribute("has", 1);
			getReq().setAttribute("_xh", _xh);
		}
		else
			getReq().setAttribute("has", 0);
		getReq().setAttribute("url", url);
		return "wechat/home/xh";
	}

	/**
	 * 序号考试
	 */
	@RequestMapping("/xhkaoshi")
	@ResponseBody
	public void xhkaoshi() {
		ResultData<String> rd = new ResultData<>();
		try {
			user u = (user)getReq().getSession().getAttribute("wxuser");
			xh _xh = xhServiceImpl.getByUserid(u.getOpenid());

			Date now = new Date();
			if(_xh!=null&&now.before(_xh.getLasttime())&&_xh.getLastcount()>0) {
				_xh.setLastcount(_xh.getLastcount()-1);
				xhServiceImpl.update(_xh);

				//记录使用信息
				xhlog _xhlog = new xhlog();
				_xhlog.setId(UUID.randomUUID().toString());
				_xhlog.setAddtime(new Date());
				_xhlog.setUid(u.getOpenid());
				_xhlog.setXhid(_xh.getId());
				xhLogServiceImpl.add(_xhlog);//4小时内有效

				rd.setType(1);
				rd.setMessage("系统进入中......");
			}
			else{
				rd.setType(1);
				rd.setMessage("您的序列号已过期!");
			}
		}
		catch(Exception e) {
			rd.setType(1);
			rd.setMessage("系统错误");
			e.printStackTrace();
		}
		responseJson(rd);
	}

	/**
	 * 个人中心
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/center")
	public String MyCenter() throws Exception{
		String code = getReq().getParameter("code");
		if(null != code && !"".equals(code)){
			System.out.println(code);
			OAuth2Token oa = AdvancedUtil.getOauth2AccessToken(Configuration.getOAuthAppId(), Configuration.getOAuthSecret(),code);
			if(!"".equals(oa) && null != oa){
				user temUser = wxUserServiceImpl.queryById(oa.getOpenid());
				if(temUser==null) {
					User u = AdvancedUtil.getSNSUserInfo(oa.getAccess_token(), oa.getOpenid());
					temUser = new user();
					temUser.setId(UUID.randomUUID().toString());
					temUser.setOpenid(u.getOpenid());
					temUser.setCity(u.getCity());
					temUser.setCountry(u.getCountry());
					temUser.setGroupid(u.getGroupid());
					temUser.setHeadimgurl(u.getHeadimgurl());
					temUser.setLanguage(u.getLanguage());
					temUser.setNickname(u.getNickname());
					temUser.setProvince(u.getProvince());
					temUser.setRemark(u.getRemark());
					temUser.setSex(String.valueOf(u.getSex()));
					temUser.setSubscribe(u.getSubscribe());
					temUser.setSubscribe_time(new Date(u.getSubscribe_time()*1000L));
					temUser.setQr_scene_str(u.getQr_scene_str());
					wxUserServiceImpl.add(temUser);
					
					getReq().getSession().setAttribute("wxuser", temUser);
				}
				else 
					getReq().getSession().setAttribute("wxuser", temUser);
				SetInfo();
				return "wechat/home/center";
			}else{//登录失败
				return "wechat/home/noright";
			}
		}
		else{
			user u = (user)getReq().getSession().getAttribute("wxuser");
			if(u==null)
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configuration.getOAuthAppId()+"&redirect_uri=http%3a%2f%2f2.zydkj.net.cn%2fwx%2fcenter&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			else {
				SetInfo();
				return "wechat/home/center";
			}
		}
	}

	private void SetInfo() throws Exception {
		Weixin wx = new Weixin();
		wx.login(Configuration.getOAuthAppId(), Configuration.getOAuthSecret());

		user u = (user)getReq().getSession().getAttribute("wxuser");

		String url = wx.createQrcode(TicketType.QR_SCENE,"F:\\aa.jpg",u.getOpenid(),3600);
		getReq().setAttribute("imgurl", url);
		getReq().setAttribute("nickname", u.getNickname());
		getReq().setAttribute("headimgurl", u.getHeadimgurl());
		getReq().setAttribute("sex", u.getSex().equals("0")?"未知":(u.getSex().equals("1")?"男":"女"));
		getReq().setAttribute("money", u.getCurrentmoney()==null?0:u.getCurrentmoney());
		getReq().setAttribute("totalmoney", u.getTotalmoney()==null?0:u.getTotalmoney());

		List<user> secUserList = wxUserServiceImpl.getSecUser(u.getOpenid());
		if(secUserList!=null)
			getReq().setAttribute("sharecount", secUserList.size());
		else
			getReq().setAttribute("sharecount", 0);


		SYSCodeBean codebean = sYSCodeServiceImpl.queryById("005");//一级
		SYSCodeBean codebean2 = sYSCodeServiceImpl.queryById("006");//一级

		getReq().setAttribute("money1", Double.valueOf(codebean.getValue())*100);
		getReq().setAttribute("money2", Double.valueOf(codebean2.getValue())*100);
	}
	
	/**
	 * 分享有礼
	 * @return
	 * @throws WeixinException 
	 */
	@RequestMapping("/share")
	public String MyShare(String skey) throws WeixinException{
		Weixin wx = new Weixin();
		wx.login(Configuration.getOAuthAppId(), Configuration.getOAuthSecret());

		String openid = "";
		if(CommonUtil.isNullObject(skey)) {
			user u = (user)getReq().getSession().getAttribute("wxuser");
			openid=u.getOpenid();
		}
		else {
			openid = skey;
		}

		String urlt = getReq().getRequestURL().toString();
		String urltemp = urlt;
		if(getReq().getQueryString()!=null)urlt = urlt+"?"+getReq().getQueryString();
		else urltemp = urltemp +"?skey="+openid;

		String url = wx.createQrcode(TicketType.QR_SCENE,"F:\\aa.jpg",openid,3600);

		JsApiTicket ticket = wx.getJsApi_Ticket();
		String noceStr = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

		getReq().setAttribute("appId", Configuration.getOAuthAppId());
		getReq().setAttribute("timestamp", timestamp);
		getReq().setAttribute("nonceStr", noceStr);
		getReq().setAttribute("signature", SignUtil.getSignature(ticket.getTicket(), noceStr, timestamp, urlt));
		getReq().setAttribute("urltemp", urltemp);

		getReq().setAttribute("imgurl", url);
		return "wechat/home/share";
	}
}
